

/**
 * 老方式演示传递代码给方法，控制其行为
 *
 * @author huangy
 * @since 2022/8/24 8:59 下午
 */

public class Strategize {

    Strategy strategy = new Soft();
    String msg;

    Strategize(String msg) {
        this.msg = msg;
    }

    void communicate() {
        System.out.println(strategy.approach(msg));
    }

    void changeStrategy(Strategy strategy) {
        this.strategy = strategy;
    }

    public static void main(String[] args) {
        //定义的不同的行为
        Strategy[] strategies = {new Soft(), new Hard(), new Strategy() {
            @Override
            public String approach(String msg) {
                return "very funny, ha ha ha!! " + msg;
            }
        }, msg -> msg.substring(0, 4), UnRelate::twice};
        Strategize strategize = new Strategize("hello world");
        strategize.communicate();
        for (Strategy strategy : strategies) {
            strategize.changeStrategy(strategy);
            strategize.communicate();
        }
    }

}

/**
 * @author huangy
 * @since 2022/8/24 9:02 下午
 **/
interface Strategy {
    String approach(String msg);
}

/**
 * 小写形式
 *
 * @author huangy
 * @since 2022/8/24 9:04 下午
 **/
class Soft implements Strategy {

    @Override
    public String approach(String msg) {
        return msg.toLowerCase() + "?";
    }
}

/**
 * 大写形式
 *
 * @author huangy
 * @since 2022/8/24 9:04 下午
 **/
class Hard implements Strategy {

    @Override
    public String approach(String msg) {
        return msg.toUpperCase() + "!";
    }

}

/**
 * 重复形式
 *
 * @author huangy
 * @since 2022/8/24 9:04 下午
 **/
class UnRelate {
    static String twice(String msg) {
        return msg + " " + msg;
    }
}




